package org.shangda.wechat.pet.util;


import com.power.common.util.DateTimeUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

/**
 * qq邮箱发送邮件工具类
 */
@Slf4j
public class MailUtil {

	/**
	 * 发送消息给客服
	 * @param username 邮箱号
	 * @param password 密码
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * @param receivers 收件人，多个收件使用英文逗号分隔
	 */
	public static void sendMail(String username, String password, String subject, String content, String receivers, File... file){
		try {
			Properties properties = new Properties();
			properties.put("mail.transport.protocol", "smtp");// 连接协议
			properties.put("mail.smtp.host", "smtp.exmail.qq.com");// 主机名
			properties.put("mail.smtp.port", 465);// 端口号
			properties.put("mail.smtp.auth", "true");
//			properties.put("mail.smtps.ssl.enable", "true");
			properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
//			properties.put("mail.smtp.starttls.enable", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
			properties.put("mail.smtp.timeout", 80000); //设置超时时间80s

			//企业邮箱必须要SSL
			MailSSLSocketFactory sf = null;
			try {
				sf = new MailSSLSocketFactory();
				sf.setTrustAllHosts(true);
			} catch (GeneralSecurityException e1) {
				e1.printStackTrace();
			}
			properties.put("mail.smtp.ssl.enable", "true");
			properties.put("mail.smtp.ssl.socketFactory", sf);


			// 得到会话对象
			Session session = Session.getInstance(properties);
			// 获取邮件对象
			javax.mail.Message message = new MimeMessage(session);
			// 设置发件人邮箱地址
			message.setFrom(new InternetAddress(username));
			String[] receiveAddresses = receivers.split(",");
			// 设置收件人邮箱地址
			log.info("发送邮件给客服人数>>>>>>>长度："+receiveAddresses.length);
			if(receiveAddresses.length > 1){
				InternetAddress[] internetAddresses = new InternetAddress[receiveAddresses.length];
				for(int i=0; i<receiveAddresses.length; i++){
					internetAddresses[i] = new InternetAddress(receiveAddresses[i]);
				}
				message.setRecipients(javax.mail.Message.RecipientType.TO, internetAddresses);//多个收件人
			}else if(receiveAddresses.length == 1){
				message.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(receiveAddresses[0]));//一个收件人
			}else {
				throw new RuntimeException("收件人地址不能为空");
			}
			// 设置邮件标题
			message.setSubject(subject);
			// 设置邮件内容
			Multipart mainPart = new MimeMultipart();
			BodyPart bodyPart = new MimeBodyPart();
//			bodyPart.setContent(content,"text/html; charset=utf-8");
			bodyPart.setText(content);

			if(null != file && file.length > 0) {
				// 附件消息
				BodyPart attachBodyPart = new MimeBodyPart();
				attachBodyPart.setFileName(MimeUtility.encodeText(file[0].getName(), "GBK", "B"));
				//从msg拿出正文及附件的信息
				DataSource fileDataSource = new FileDataSource(file[0]);
				attachBodyPart.setDataHandler(new DataHandler(fileDataSource));
				mainPart.addBodyPart(attachBodyPart);
			}
			mainPart.addBodyPart(bodyPart);
			message.setContent(mainPart);
			// 得到邮差对象
			Transport transport = session.getTransport();
			// 连接自己的邮箱账户
			transport.connect(username, password);// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
			// 发送邮件
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			log.info("发送邮件给客服成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("发送邮件给客服异常, exception:", e);
		}
	}



	public static void main(String[] args) throws Exception{
//		System.out.println(getDeliveryContent());
//		System.out.println(getPreOrderContent());
//		System.out.println(getRemarkContent());

		String content = "Hi Kevin,\n\n截止至@TODAY@，BV天猫会员增长数据如下：\n\n-入会总数：@ADD_MEMBER_TOTOAL_COUNT@\n\n-已有明文手机号：@MEMBER_WITH_MOBILE_TOTAL_COUNT@\n\n-今日入会总数（@YESTERDAY@-@TODAY@）：@TODAY_ADD_MEMBER_COUNT@\n\n-今日新增手机号（@YESTERDAY@-@TODAY@）：@TODAY_MEMBER_WITH_MOBILE_COUNT@";

		String today = DateTimeUtil.dateToStr(new Date(), DateTimeUtil.DATE_FORMAT_DAY) + " 18:00";
		Date yesterdayDate = DateUtils.addDays(new Date(), -1);
		String yesterday = DateTimeUtil.dateToStr(yesterdayDate, DateTimeUtil.DATE_FORMAT_DAY) + " 18:00";
		Long addMemberTotoalCount = 100L;
		Long memberWithMobileTotalCount = 80L;
		Long todayAddMemberCount = 10L;
		Long todayMemberWithMobileCount = 10L;


		content = content.replaceAll("@TODAY@", today)
		.replaceAll("@YESTERDAY@", yesterday)
		.replaceAll("@ADD_MEMBER_TOTOAL_COUNT@", addMemberTotoalCount.toString())
		.replaceAll("@MEMBER_WITH_MOBILE_TOTAL_COUNT@", memberWithMobileTotalCount.toString())
		.replaceAll("@TODAY_ADD_MEMBER_COUNT@", todayAddMemberCount.toString())
		.replaceAll("@TODAY_MEMBER_WITH_MOBILE_COUNT@", todayMemberWithMobileCount.toString());

		System.out.println(content);
//		sendMail("jason.zhu@d1m.cn","ZS@jason20190227!!!","【BV】天猫会员数据Daily Report", content,"jason.zhu@d1m.cn");
		File file2 = new File("/Users/shengzhu/Desktop/tt.jpeg");
		sendMail("palace@d1mgroup.com","sqlm1D1234","【BV】天猫会员数据Daily Report", content,"jason.zhu@d1m.cn", file2);

	}
}
